package com.guapi.controller;

import com.guapi.entity.Goods;
import com.guapi.entity.Page;
import com.guapi.entity.User;
import com.guapi.service.GoodsService;
import com.guapi.service.UserService;
import com.guapi.util.HostHolder;
import com.guapi.util.MallConstant;
import com.guapi.util.MallUtil;
import com.guapi.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController implements MallConstant {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;


    @RequestMapping(path = "/show/{pattern}", method = RequestMethod.GET)
    public String getGoodsPage(@PathVariable("pattern") int pattern, Page page, Model model) {

        page.setRows(goodsService.findGoodsCount(GOODS_STATUS_ACTIVE));
        page.setPath("/goods/show/" + pattern);

        //page.setPath("/show/"+pattern+"/"+limit+"/"+sort);
        //model.addAttribute("pattern", pattern);
        //model.addAttribute("sort",sort);
        //model.addAttribute("page",page);

        if (pattern == GOODS_SHOW_LIST) {
            page.setLimit(5);
            List<Goods> goodsList = goodsService.findGoodsList(0, GOODS_STATUS_ACTIVE, page.getOffset(), page.getLimit());
            model.addAttribute("goodsList", goodsList);
            return "site/goodsList";
        } else if (pattern == GOODS_SHOW_GRID) {
            page.setLimit(12);
            List<Goods> goodsList = goodsService.findGoodsList(0, GOODS_STATUS_ACTIVE, page.getOffset(), page.getLimit());
            model.addAttribute("goodsList", goodsList);
            return "site/goodsGrid";
        } else {
            throw new IllegalArgumentException("你访问的路径有误，请返回主页");
        }
        //goodsService.showGoods(pattern);
    }

    @RequestMapping(path = "/show", method = RequestMethod.POST)
    public String showGoods() {
        System.out.println("进入了showGoods方法");
        return null;
    }


    @RequestMapping(path = "/addCart/{goodsId}", method = RequestMethod.POST)
    @ResponseBody
    public String addShoppingCart(@PathVariable("goodsId") int goodsId) {

        long createTime = System.currentTimeMillis();
        User user = hostHolder.getUser();
        Goods goods = goodsService.findGoodsById(goodsId);
        if (user == null) {
            throw new IllegalArgumentException("用户未登录，请登录");
        } else if (goods == null) {
            throw new IllegalArgumentException("该商品不存在或已被买走");
        }
        String redisKey = RedisKeyUtil.getUserShoppingCartKey(user.getId());
        redisTemplate.opsForZSet().add(redisKey, goods, createTime);
        //然后呢？该回到原页面，并且在原商品处标记已加入购物车，并停用button
        //还是说通过js处理这一次请求，在前端处理请求后
        return MallUtil.getJSONString(0);
    }

    @RequestMapping(path = "/showCart", method = RequestMethod.GET)
    public String getShoppingCartPage(Model model) {

        return "site/shoppingCart";
    }

    @RequestMapping(path = "/removeCart/{goodsId}", method = RequestMethod.GET)
    @ResponseBody
    public String removeCartGoods(@PathVariable("goodsId") int goodsId) {
        User user = hostHolder.getUser();

        Long result = goodsService.removeCartGoods(user, goodsId);
        if (result==1){
            return MallUtil.getJSONString(0,"删除成功");
        }
        else {
            return MallUtil.getJSONString(1,"删除失败，出现了某些错误");
        }
    }

    @RequestMapping(path = "/publish", method = RequestMethod.GET)
    public String getPublishPage() {
        return "/site/publish";
    }

    @RequestMapping(path = "/publish",method = RequestMethod.POST)
    public String publishGoods(String title,String goodsName, Integer price,Integer number,String detail,Model model){
        User user = hostHolder.getUser();
        if (user==null){
            throw new IllegalArgumentException("用户未登录");
        }
        Goods goods = new Goods();
        goods.setGoodsName(goodsName);
        goods.setDetail(detail);
        goods.setTitle(title);
        goods.setPrice(price);
        goods.setCreateTime(new Date());
        //记录发布者id
        goods.setUserId(user.getId());
        goods.setTypes(GOODS_STATUS_ACTIVE);
        //goods.setScore();

        //将商品存入数据库
        int result = goodsService.addGoods(goods);


        //发布成功返回主页或者传出成功消息？或者传出成功消息后返回主页？
        if (result==1){
            model.addAttribute("msg","发布成功，点击确定返回至主页");
        }else {
            model.addAttribute("msg","发布失败，出现了不可预知的错误，请稍后再来");
        }
        model.addAttribute("result",result);
        return "site/publish";
    }

    @RequestMapping(path = "/detail/{goodsId}" ,method = RequestMethod.GET)
    public String getGoodsDetailPage(@PathVariable(name = "goodsId")int goodsId,Model model){
        Goods goods = goodsService.findGoodsById(goodsId);
        User user = userService.findUserById(goods.getUserId());
        model.addAttribute("user",user);
        model.addAttribute("goods",goods);
        return "site/goodsDetail";
    }

}
